package action;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.actions.DispatchAction;
import entitybean.l_sequence.EntityBeanL_Sequence;
import entitybean.oc_operator_user.EntityBeanOc_Operator_User;
import entitybean.oc_user_name.EntityBeanOc_User_Name;
import entitybean.rolepower.EntityBeanRolepower;
import entitybean.system_log.EntitybeanSystem_Log;
import entitybean.systemtree.EntityBeanSystemtree;
import service.service_public.Service_Public;
import service.service_login.Service_Login;
import tools.HttpTools;
import tools.SendMail;

public class Action_Login extends DispatchAction {
	private Service_Public service_public;
	private Service_Login service_login;

	public Service_Login getService_login() {
		return service_login;
	}

	public void setService_login(Service_Login service_login) {
		this.service_login = service_login;
	}

	public Service_Public getService_public() {
		return service_public;
	}

	public void setService_public(Service_Public service_public) {
		this.service_public = service_public;
	}

	public ActionForward show_systemtree(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		System.out.println("展示系统结构树");

		String c_jd = request.getParameter("q");
		String lv = request.getParameter("lv");
		lv = String.valueOf(Integer.valueOf(lv) + 1);
		List<EntityBeanSystemtree> systemtreelist = this.service_login
				.Find_SystemTree_By_c_jd(Integer.valueOf(c_jd));
		request.setAttribute("systemtreelist", systemtreelist);
		request.setAttribute("lv", lv);
		return mapping.findForward("success");
	}

	public ActionForward init_updatepassword(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		System.out.println("尝试载入密码修改页面~");
		System.out.println("校验用户信息");

		EntityBeanOc_User_Name e = new EntityBeanOc_User_Name();
		e = (EntityBeanOc_User_Name) request.getSession().getAttribute(
				"Ocean_User");
		if (e == null) {
			System.out.println("会话变量丢失");
			return mapping.findForward("error");
		} else {
			return mapping.findForward("success");
		}

	}
private String Compare_Time(String s1,String s2)
{
	java.text.DateFormat df=new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	java.util.Calendar c1=java.util.Calendar.getInstance();

	java.util.Calendar c2=java.util.Calendar.getInstance();

	try{

	  c1.setTime(df.parse(s1));

	  c2.setTime(df.parse(s2));

	}catch(java.text.ParseException e){

	  System.err.println("格式不正确");

	}
	int result=c1.compareTo(c2);
	if(result==0)
	{
	  System.out.println("c1相等c2");
	  return "0";
	}
	else if(result<0)
	{
	  System.out.println("c1小于c2");
	  return "-1";
	}
	else
	{
	  System.out.println("c1大于c2");
	  return "1";
	}
}
	public ActionForward updatepassword(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		System.out.println("尝试更新用户的密码");
		DynaActionForm loginform = (DynaActionForm) form;
		String password = (String) loginform.getString("password");
		String newpassword = (String) loginform.getString("newpassword");
		String re_newpassword = (String) loginform.getString("re_newpassword");
		String yzm = (String) loginform.getString("yzm");
		System.out.println("password=" + password);
		System.out.println("newpassword=" + newpassword);
		System.out.println("re_newpassword=" + re_newpassword);
		System.out.println("yzm=" + yzm);
		String S_yzm = (String) request.getSession().getAttribute("rand");
		if (!S_yzm.equals(yzm)) {
			System.out.println("验证码错误");
			String error_msg = "验证码错误~";
			request.setAttribute("error_msg", error_msg);
			return mapping.findForward("success");
		}

		EntityBeanOc_User_Name e = new EntityBeanOc_User_Name();
		e = (EntityBeanOc_User_Name) request.getSession().getAttribute(
				"Ocean_User");
		if (e == null) {
			System.out.println("会话变量丢失");
			return mapping.findForward("error");
		} else {
			System.out.println("读取会话变量中的信息");
			System.out.println("e.getUsername()=" + e.getUsername());
			System.out.println("e.getPassword()=" + e.getPassword());
			EntityBeanOc_User_Name u = this.service_login
					.Find_EntityBeanOc_User_Name(e.getUsername(), e
							.getPassword());
			if (password.equals(u.getPassword())) {
				u.setPassword(newpassword);
				EntityBeanL_Sequence l = this.service_public
						.Find_L_Sequence_By_seq_Name("SEQ_SYSTEM_LOG");
				Integer id = l.getSeq_Value() + 1;
				HttpTools httptools = new HttpTools();
				String ip = httptools.getIpAddr(request);
				l.setSeq_Value(id);
				EntitybeanSystem_Log log = new EntitybeanSystem_Log();
				log.setId(id);
				log.setIp(ip);
				log.setLog_kind("更新");
				log.setUpdate_time(new Date());
				log.setUser_id(e.getId());
				log.setAction("用户修改了新的用户密码，用户名=" + e.getUsername() + " 旧密码="
						+ password + " 新密码=" + u.getPassword());
				log.setFinish("成功");
				// 写入日志
				this.service_public.Update_L_Sequence(l);
				this.service_public.Insert_System_Log(log);
				this.service_login.Update_Oc_User_Name(u);
				request.getSession().setAttribute("Ocean_User", u);
				String error_msg = "用户密码更新成功~";
				request.setAttribute("error_msg", error_msg);
				return mapping.findForward("success");
			} else {
				String error_msg = "输入的用户密码错误~";
				request.setAttribute("error_msg", error_msg);
				return mapping.findForward("success");
			}
		}
	}

	public ActionForward quit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		DynaActionForm loginform = (DynaActionForm) form;
		String id = (String) loginform.getString("username");
		System.out.println("quitform.getUsername_id=" + id);
		Date d = new Date();
		HttpTools httptools = new HttpTools();
		String ip = httptools.getIpAddr(request);
		EntityBeanOc_User_Name e = this.service_login
				.Find_EntityBeanOc_User_Name_By_ID(Integer.valueOf(id));
		e.setLast_action(d);

		// 记录登出系统的操作日志
		// 清空session资料
		// 更新操作最后一个记录
		EntityBeanL_Sequence sequence = this.service_public
				.Find_L_Sequence_By_seq_Name("SEQ_SYSTEM_LOG");
		sequence.setSeq_Value(sequence.getSeq_Value() + 1);
		EntitybeanSystem_Log log = new EntitybeanSystem_Log();
		log.setAction("用户退出系统，用户名=" + e.getUsername() + ",密码="
				+ e.getPassword());
		log.setId(sequence.getSeq_Value());
		log.setIp(ip);
		log.setLog_kind("登出");
		log.setUpdate_time(d);
		log.setUser_id(Integer.valueOf(id));
		this.service_public.Update_L_Sequence(sequence);
		this.service_public.Insert_System_Log(log);
		System.out.println("更新操作最后一个记录");
		this.service_login.Update_Oc_User_Name(e);
		System.out.println("清空session资料");
		request.getSession().setAttribute("Ocean_User", null);
		request.getSession().setAttribute("Ocean_Login", null);
		return mapping.findForward("success");
	}

	public ActionForward admin_login(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		DynaActionForm loginform = (DynaActionForm) form;
		String username = loginform.getString("username");
		String password = loginform.getString("password");

		System.out.println("username=" + username);
		System.out.println("password=" + password);
		EntityBeanOc_User_Name e = this.service_login.Find_EntityBeanOc_User_Name_Admin(username, password);
		if (e.getId() != null)
		{
			System.out.println("用户名校验通过");
			System.out.println("判断用户有效时间是否过期");
			Date d1=new Date();
			String s1=this.ConvertDateToString(d1, "yyyy-MM-dd HH:mm:ss");
			String s2=this.ConvertDateToString(e.getLast_action(),"yyyy-MM-dd HH:mm:ss" );
			if(this.Compare_Time(s1, s2).equals("1"))
			{
				System.out.println("用户账号过期");
				HttpTools httptools = new HttpTools();
				String ip = httptools.getIpAddr(request);

				System.out.println("保存操作日志");
				EntityBeanL_Sequence l = new EntityBeanL_Sequence();
				l = this.service_public
						.Find_L_Sequence_By_seq_Name("SEQ_SYSTEM_LOG");
				Integer id = l.getSeq_Value();
				id = id + 1;
				l.setSeq_Value(id);
				EntitybeanSystem_Log system_log = new EntitybeanSystem_Log();
				system_log.setId(id);
				system_log.setAction("用户名校验通过,用户名=" + username + ",密码=" + password+",但是用户有效期过期："+e.getLast_action());
				system_log.setUpdate_time(new Date());
				system_log.setLog_kind("登入");
				system_log.setUser_id(e.getId());
				system_log.setIp(ip);
				system_log.setFinish("失败");
				Date d = new Date();
				e.setLogin_time(d);
				e.setLast_action(d);
				this.service_login.Update_Oc_User_Name(e);
				this.service_public.Update_L_Sequence(l);
				this.service_public.Insert_System_Log(system_log);
				request.setAttribute("error_msg", "用户已经过期");
				request.getSession().setAttribute("Ocean_User", null);
				request.getSession().setAttribute("Ocean_Login", "No");	
				request.getSession().setAttribute("IsAdmin", "No");				
				return mapping.findForward("error");

			}			
			
			System.out.println("开始判断权限大小");
			HashSet<Integer> powerset = new HashSet<Integer>();
			String power=e.getPower();
			if (power.equals("ON"))
			{
				System.out.println("用户没有权限");
			}
			else
			{
				String p_str[]=power.split(",");
				for(int p=0;p<p_str.length;p++)
				{
					powerset.add(Integer.valueOf(p_str[p]));
				}
				System.out.println("powerset.size()"+powerset.size());
				//根据跟节点配置子节点的权限
		       List<EntityBeanSystemtree> list_c=this.service_login.Find_SystemTree_In_c_jd(power);
				
		       for(int p=0;p<list_c.size();p++)
				{
					powerset.add(Integer.valueOf(list_c.get(p).getF_jd()));
				}
		       System.out.println("powerset.size()"+powerset.size());
			}
			
			
			
		
			List<EntityBeanSystemtree> entitybeanSystemtreelist = this.service_login
			.Find_SystemTree_By_c_jd(0);
			int seconds=30*24*60*60;   
			Cookie cookie = new Cookie("user", username+"=="+password);   
			cookie.setMaxAge(seconds);                      
			response.addCookie(cookie);  
			request.getSession().setAttribute("listSystemtree",
					entitybeanSystemtreelist);
			request.getSession().setAttribute("RolePower", powerset);
			request.getSession().setAttribute("Ocean_User", e);
			request.getSession().setAttribute("Ocean_Login", "Yes");	
			request.getSession().setAttribute("IsAdmin", "Yes");
			return mapping.findForward("success");
		}
		else
		{
			HttpTools httptools = new HttpTools();
			String ip = httptools.getIpAddr(request);
			EntityBeanL_Sequence l = new EntityBeanL_Sequence();
			l = this.service_public
					.Find_L_Sequence_By_seq_Name("SEQ_SYSTEM_LOG");
			Integer id = l.getSeq_Value();
			id = id + 1;
			l.setSeq_Value(id);
			EntitybeanSystem_Log system_log = new EntitybeanSystem_Log();
			system_log.setId(id);
			system_log.setAction("用户名校验失败,用户名=" + username + ",密码=" + password);
			system_log.setUpdate_time(new Date());
			system_log.setLog_kind("管理员登入");
			system_log.setUser_id(0);
			system_log.setIp(ip);
			system_log.setFinish("失败");
			Date d = new Date();
			e.setLogin_time(d);
			this.service_public.Update_L_Sequence(l);
			this.service_public.Insert_System_Log(system_log);
			
			request.getSession().setAttribute("Ocean_User", null);
			request.getSession().setAttribute("Ocean_Login", "No");	
			request.getSession().setAttribute("IsAdmin", "No");
			request.setAttribute("error_msg", "用户名不是管理员或者密码错误");
			return mapping.findForward("error");
		}
	}
	private String ConvertDateToString(Date d, String foramt) {
		SimpleDateFormat sdf = new SimpleDateFormat(foramt);
		String str = sdf.format(d);
		return str;
	}
	public ActionForward login(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		/*
		 * 逻辑：采集用户名+密码的组合，在数据库中校验。如果存在则赋予sessoin变量，记录日志，放行。
		 * 如果不存在则告知用户名密码错误。返回原来的页面
		 */
		DynaActionForm loginform = (DynaActionForm) form;
		String username = loginform.getString("username");
		String password = loginform.getString("password");
		String autologin = loginform.getString("autologin");
		String Ocean_Login = null;// 标记到session中该用户是否为登录状态
		EntityBeanOc_User_Name Ocean_User = new EntityBeanOc_User_Name();
		// Ocean_Login = (String)
		// request.getSession().getAttribute("Ocean_Login");
		// Ocean_User=(EntityBeanOc_User_Name)request.getSession().getAttribute("Ocean_User");
		System.out.println("Ocean_Login=" + Ocean_Login);
		System.out.println("loginform.getUsername=" + username);
		System.out.println("loginform.getPassword=" + password);
		System.out.println("开始校验用户名和密码");
		EntityBeanOc_User_Name e = new EntityBeanOc_User_Name();
		e = this.service_login.Find_EntityBeanOc_User_Name(username, password);
		if (e.getId() != null) {
			System.out.println("用户名校验通过");
			System.out.println("判断用户有效时间是否过期");
			Date d1=new Date();
			
			
			String s1=this.ConvertDateToString(d1, "yyyy-MM-dd HH:mm:ss");
			String s2=this.ConvertDateToString(e.getLast_action(),"yyyy-MM-dd HH:mm:ss" );
			if(this.Compare_Time(s1, s2).equals("1"))
			{
				System.out.println("用户账号过期");
				HttpTools httptools = new HttpTools();
				String ip = httptools.getIpAddr(request);

				System.out.println("保存操作日志");
				EntityBeanL_Sequence l = new EntityBeanL_Sequence();
				l = this.service_public
						.Find_L_Sequence_By_seq_Name("SEQ_SYSTEM_LOG");
				Integer id = l.getSeq_Value();
				id = id + 1;
				l.setSeq_Value(id);

				EntitybeanSystem_Log system_log = new EntitybeanSystem_Log();
				system_log.setId(id);
				system_log.setAction("用户名校验通过,用户名=" + username + ",密码=" + password+",但是用户有效期过期："+e.getLast_action());
				system_log.setUpdate_time(new Date());
				system_log.setLog_kind("登入");
				system_log.setUser_id(e.getId());
				system_log.setIp(ip);
				system_log.setFinish("失败");
				Date d = new Date();
				e.setLogin_time(d);
				e.setLast_action(d);
				this.service_login.Update_Oc_User_Name(e);
				this.service_public.Update_L_Sequence(l);
				this.service_public.Insert_System_Log(system_log);
				request.setAttribute("error_msg", "用户已经过期");
				return mapping.findForward("error");

			}			
			System.out.println("loginform.getAutologin=" + autologin);
			System.out.println("开始校验是否选择了保存状态的设定");
			if (autologin.equals("autologin")) {
				System.out.println("为用户设置COOKIE,保证其下次可以正常登录");
			}

			System.out.println("开始判断权限大小");

			HttpTools httptools = new HttpTools();
			String ip = httptools.getIpAddr(request);

			System.out.println("保存操作日志");
			EntityBeanL_Sequence l = new EntityBeanL_Sequence();
			l = this.service_public
					.Find_L_Sequence_By_seq_Name("SEQ_SYSTEM_LOG");
			Integer id = l.getSeq_Value();
			id = id + 1;
			l.setSeq_Value(id);

			EntitybeanSystem_Log system_log = new EntitybeanSystem_Log();
			system_log.setId(id);
			system_log.setAction("用户名校验通过,用户名=" + username + ",密码=" + password);
			system_log.setUpdate_time(new Date());
			system_log.setLog_kind("登入");
			system_log.setUser_id(e.getId());
			system_log.setIp(ip);
			system_log.setFinish("成功");
			Date d = new Date();
			e.setLogin_time(d);
			//e.setLast_action(d);
			this.service_login.Update_Oc_User_Name(e);
			this.service_public.Update_L_Sequence(l);
			this.service_public.Insert_System_Log(system_log);
			System.out.println("选择跳转方向");
			request.getSession().setAttribute("Ocean_User", e);
			request.getSession().setAttribute("Ocean_Login", "Yes");
			request.getSession().setAttribute("IsAdmin", "No");

			return mapping.findForward("success");
		} else {
			request.setAttribute("error_msg", "错误的用户名和密码~");
			System.out.println("用户名校验未通过");
			System.out.println("保存操作日志");

			EntityBeanL_Sequence l = new EntityBeanL_Sequence();
			l = this.service_public
					.Find_L_Sequence_By_seq_Name("SEQ_SYSTEM_LOG");
			Integer id = l.getSeq_Value();
			id = id + 1;
			l.setSeq_Value(id);

			HttpTools httptools = new HttpTools();
			String ip = httptools.getIpAddr(request);

			EntitybeanSystem_Log system_log = new EntitybeanSystem_Log();
			system_log.setId(id);
			system_log
					.setAction("用户名校验未通过,用户名=" + username + ",密码=" + password);
			system_log.setUpdate_time(new Date());
			system_log.setLog_kind("登入");
			system_log.setUser_id(0);
			system_log.setFinish("失败");
			system_log.setIp(ip);

			this.service_public.Update_L_Sequence(l);
			this.service_public.Insert_System_Log(system_log);
			request.getSession().setAttribute("Ocean_User", null);
			request.getSession().setAttribute("Ocean_Login", "No");
			request.getSession().setAttribute("IsAdmin", "No");

			System.out.println("选择跳转方向");
			request.setAttribute("error_msg", "错误的用户名或者密码,或者用户处于未激活状态");
			return mapping.findForward("error");

		}
	}

	public ActionForward init_login_out(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		EntityBeanOc_User_Name Ocean_User = new EntityBeanOc_User_Name();
		Ocean_User = (EntityBeanOc_User_Name) request.getSession()
				.getAttribute("Ocean_User");
		return mapping.findForward("success");

	}
	public ActionForward find_password(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		DynaActionForm loginform = (DynaActionForm) form;
		String email = request.getParameter("email");
		EntityBeanOc_User_Name entity=this.service_login.Find_EntityBeanOc_By_Email(email);
		if(!"".equals(entity.getUsername())&&entity.getUsername()!=null){
			  SendMail cn = new SendMail();
			  // 设置发件人地址、收件人地址和邮件标题
			  cn.setAddress("r5094@163.com", email, "找回密码"); 
	          cn.send("你的账号为："+entity.getUsername()+",你的密码为："+entity.getPassword());
	    	  request.setAttribute("msg", 1);
		}else{
			request.setAttribute("msg", 2);
		}
	   return mapping.findForward("success");

	}

}
